package com.forum.controller;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.forum.business.ForumManager;
import com.forum.model.dao.PostDAO;
import com.forum.model.dao.TopicDAO;
import com.forum.model.pojo.Post;
import com.forum.model.pojo.Topic;

@WebServlet("/PostController")
public class PostController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {	
		long topicId;
		TopicDAO topicDao = new TopicDAO();
		
		if (request.getParameter("sectionName") != null) {
			Topic topic = ForumManager.fillTopicData(request);
			topicDao.insert(topic);
			topicId = topic.getId();
		} else {
			topicId = Long.valueOf(request.getParameter("topicId"));
			Topic topic = topicDao.getObjectById(topicId);
			topic.setModifyDate(new Date());
			topicDao.update(topic);
		}
		
		Post post = ForumManager.fillPostData(request);
		post.setTopic(topicId);
		PostDAO postDao = new PostDAO();
		postDao.insert(post);
		response.sendRedirect(request.getContextPath() + "/topic.jsp?id=" + topicId + "&lang=" + request.getParameter("lang"));
	}
}